package com.bawei.mall.product.service.impl;

import com.bawei.common.core.domain.R;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.cart.domain.reponse.MallProductCartVo;
import com.bawei.mall.product.domain.MallCalcAmount;
import com.bawei.mall.product.domain.MallProductAddrs;
import com.bawei.mall.product.domain.MallProductOrderInfo;
import com.bawei.mall.product.domain.model.MallProductOrder;
import com.bawei.mall.product.mapper.MallProductAddrsMapper;
import com.bawei.mall.product.mapper.MallProductOrderMapper;
import com.bawei.mall.product.service.IMallProductOrderService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author：作者姓名
 * @Package：com.bawei.mall.product.service.impl
 * @Project：mall_cloud
 * @name：IMallProductOrderServiceImpl
 * @Date：2024/7/9 11:54
 */
@Service
public class IMallProductOrderServiceImpl implements IMallProductOrderService {

    @Autowired
    private MallProductOrderMapper mallProductOrderMapper;

    @Autowired
    private MallProductAddrsMapper mallProductAddrsMapper;


    @Override
    public R<MallProductOrder> selectGenerateConfirmOrder(List<Integer> cartIds) {

        //查询当前用户的地址
        Long userId = SecurityUtils.getUserId();
        List<MallProductAddrs> mallProductAddrs = mallProductAddrsMapper.selectMallProductAddrs(userId);
        if (mallProductAddrs.size() == 0) {
            return R.fail("请先添加收货地址");
        }
        MallProductOrder mallProductOrder = new MallProductOrder();
        mallProductOrder.setMemberReceiveAddressList(mallProductAddrs);

        //查询商品信息
        List<MallProductCartVo> mallProductCartVos = mallProductOrderMapper.selectmallProductCartList(cartIds);

        //转换属性
        mallProductCartVos.forEach(skuInfo -> {
            String input = skuInfo.getProductAttr();
            List<String> properties = splitProperties(input);
            String json = convertToJson(properties);
            skuInfo.setProductAttr(json);
        });

        MallCalcAmount mallCalcAmount = new MallCalcAmount();
        // 使用流计算总金额
        BigDecimal totalAmount = mallProductCartVos.stream()
                .map(item -> item.getPrice().multiply(new BigDecimal(item.getQuantity()))) // 计算每个商品的总金额
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 将所有商品的总金额相加
        // 使用流计算总优惠金额
        BigDecimal promotionAmount = mallProductCartVos.stream()
                .map(MallProductCartVo::getPromotionAmount) // 获取每个 MallProductCartVo 对象的 promotionAmount 字段值
                .filter(amount -> amount != null) // 过滤掉为 null 的值
                .reduce(BigDecimal.ZERO, BigDecimal::add); // 对所有 BigDecimal 值求和

        mallCalcAmount.setTotalAmount(totalAmount);
        mallCalcAmount.setPromotionAmount(promotionAmount);
        // 计算支付金额
        BigDecimal payAmount = totalAmount.subtract(promotionAmount);
        mallCalcAmount.setPayAmount(payAmount);
        mallCalcAmount.setFreightAmount(0);

        mallProductOrder.setCartPromotionItemList(mallProductCartVos);

        mallProductOrder.setCalcAmount(mallCalcAmount);
        List<String> couponHistoryDetailList = new ArrayList<>();
        mallProductOrder.setCouponHistoryDetailList(couponHistoryDetailList);
        return R.ok(mallProductOrder);
    }

    @Override
    @Transactional
    public void insertMallProductOrderInfo(MallProductOrderInfo mallProductOrderInfo) {
        //获取用户id
        mallProductOrderInfo.setUserId(SecurityUtils.getUserId());
        //插入订单
        mallProductOrderMapper.insertMallProductOrderInfo(mallProductOrderInfo);
        //添加中间表
        Integer id = mallProductOrderInfo.getId();
        mallProductOrderMapper.insertMallProductOrderInfoItem(id,mallProductOrderInfo.getCartIds());
        //删除购物车
        mallProductOrderMapper.deleteMallProductCart(mallProductOrderInfo.getCartIds());
    }

    private static List<String> splitProperties(String input) {
        String[] parts = input.split(",");
        List<String> properties = new ArrayList<>();
        for (String part : parts) {
            properties.add(part.trim());
        }
        return properties;
    }
    private static String convertToJson(List<String> properties) {
        Map<String, StringBuilder> propertyMap = new HashMap<>();

        // Populate property map
        for (String property : properties) {
            if (property.contains("色")) {
                String[] keyValue = property.split("色");
                if (keyValue.length == 2) {
                    if (!propertyMap.containsKey("颜色")) {
                        propertyMap.put("颜色", new StringBuilder(keyValue[1]));
                    } else {
                        propertyMap.get("颜色").append("+").append(keyValue[1]);
                    }
                } else {
                    if (!propertyMap.containsKey("颜色")) {
                        propertyMap.put("颜色", new StringBuilder(property));
                    } else {
                        propertyMap.get("颜色").append("+").append(property);
                    }
                }
            } else {
                if (!propertyMap.containsKey("容量")) {
                    propertyMap.put("容量", new StringBuilder(property));
                } else {
                    propertyMap.get("容量").append("+").append(property);
                }
            }
        }

        // Convert property map to list of Property objects
        List<Property> jsonObjects = new ArrayList<>();
        propertyMap.forEach((key, value) -> {
            jsonObjects.add(new Property(key, value.toString()));
        });

        // Convert to JSON
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(jsonObjects);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }

    // Simple Property class for storing key-value pairs
    static class Property {
        private String key;
        private String value;

        public Property(String key, String value) {
            this.key = key;
            this.value = value;
        }

        // Getters and Setters
        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}
